package com.jiangxiaofei.citycloud.activity;

import android.Manifest;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v4.widget.DrawerLayout;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.Overlay;
import com.baidu.mapapi.map.PolygonOptions;
import com.baidu.mapapi.map.Stroke;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.district.DistrictResult;
import com.baidu.mapapi.search.district.DistrictSearch;
import com.baidu.mapapi.search.district.DistrictSearchOption;
import com.baidu.mapapi.search.district.OnGetDistricSearchResultListener;
import com.bumptech.glide.Glide;
import com.jiangxiaofei.citycloud.R;
import com.jiangxiaofei.citycloud.base.BaseActivity;
import com.jiangxiaofei.citycloud.constants.Constants;
import com.jiangxiaofei.citycloud.service.LocationService;

import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import pub.devrel.easypermissions.EasyPermissions;

import static com.baidu.mapapi.map.MyLocationConfiguration.LocationMode;
import static com.baidu.mapapi.map.MyLocationConfiguration.LocationMode.COMPASS;
import static com.baidu.mapapi.map.MyLocationConfiguration.LocationMode.FOLLOWING;
import static com.baidu.mapapi.map.MyLocationConfiguration.LocationMode.NORMAL;

/**
 * Created by JiangXFei on 2017/8/10.
 */

public class MapAcitivity extends BaseActivity implements SensorEventListener ,EasyPermissions.PermissionCallbacks {
    public static final String TITLE="title";
    @InjectView(R.id.map_mapv_show)
    MapView mapMapvShow;
    @InjectView(R.id.map_drawer_menu)
    DrawerLayout mapDrawerMenu;
    @InjectView(R.id.map_rb_general)
    RadioButton mapRbGeneral;
    @InjectView(R.id.map_rb_moon)
    RadioButton mapRbMoon;
    @InjectView(R.id.map_rg_select_type)
    RadioGroup mapRgSelectType;
    @InjectView(R.id.map_rb_3d)
    RadioButton mapRb3d;
    @InjectView(R.id.map_img_mtype)
    ImageView imgMtype;
    private BaiduMap mBaiduMap;
    private String title;
    private LocationMode mCurrentMode;
    private LocationClient mLocClient;
    String[] perms = {Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.READ_PHONE_STATE};
    public BDLocationListener myListener = new MyLocationListenner();
    private Overlay mPolygon;
    private int defaultColor;
    private BitmapDescriptor mCurrentMarker;
    private SensorManager mSensorManager;
    private MapStatus.Builder builder;
    private LatLng ll;
    boolean isFirstLoc = true; // 是否首次定位
    private Double lastX = 0.0;
    private int mCurrentDirection = 0;
    private double mCurrentLat = 0.0;
    private double mCurrentLon = 0.0;
    private float mCurrentAccracy;
    private MyLocationData locData;

    @Override
    protected void initView(Bundle savedInstanceState) {
        mActivity = this;
        mContext = this;
        setContentView(R.layout.activity_map_layout);
        title = getIntent().getStringExtra(TITLE);
        ButterKnife.inject(this);
        initTitle();
        if (EasyPermissions.hasPermissions(this, perms)) {
            initMap();
            initShowView();
            mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION),
                    SensorManager.SENSOR_DELAY_UI);
        } else {
            EasyPermissions.requestPermissions(this, "使用此功能需要读取您授予以下权限。",
                    200, perms);
        }
        ColorStateList textColors = mapRbGeneral.getTextColors();
        defaultColor = textColors.getDefaultColor();
        mapRbMoon.setTextColor(Color.RED);
    }

    private void initShowView() {
        mapDrawerMenu.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
        mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);// 获取传感器管理服务
    }

    //初始化地图层
    private void initMap() {
        mBaiduMap = mapMapvShow.getMap();
        mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL); //设置为普通模式的地图
        mCurrentMode = NORMAL;
        mBaiduMap
                .setMyLocationConfigeration(new MyLocationConfiguration(
                        mCurrentMode, true, null));
        // 开启定位图层
        mBaiduMap.setMyLocationEnabled(true);
        mLocClient = new LocationClient(this);  //定位用到的一个类
        mLocClient.registerLocationListener(myListener); //注册监听

        ///LocationClientOption类用来设置定位SDK的定位方式，
        LocationClientOption option = new LocationService(mContext).getDefaultLocationClientOption(); //以下是给定位设置参数
        mLocClient.setLocOption(option);
        mLocClient.start();
        DistrictSearch mDistrictSearch = DistrictSearch.newInstance();
        mDistrictSearch.setOnDistrictSearchListener(listener);//设置回调监听

        DistrictSearchOption districtSearchOption = new DistrictSearchOption();
        if (Constants.bdLocation!= null) {
            districtSearchOption.cityName(Constants.bdLocation.getCity());//检索城市名称
        } else {
            districtSearchOption.cityName("青岛市");//检索城市名称
        }
//        districtSearchOption.districtName(districtStr);//检索的区县名称
        mDistrictSearch.searchDistrict(districtSearchOption);//请求行政区数据
    }

    //获取地位行政区边框线
    OnGetDistricSearchResultListener listener = new OnGetDistricSearchResultListener() {

        @Override
        public void onGetDistrictResult(DistrictResult districtResult) {
            districtResult.getCenterPt();//获取行政区中心坐标点
            districtResult.getCityName();//获取行政区域名称
            List<List<LatLng>> polyLines = districtResult.getPolylines();//获取行政区域边界坐标点
            //边界就是坐标点的集合，在地图上画出来就是多边形图层。有的行政区可能有多个区域，所以会有多个点集合。
            PolygonOptions polygonOptions = new PolygonOptions();
            polygonOptions.points(polyLines.get(0));//多边形顶点坐标集
            polygonOptions.stroke(new Stroke(5, 0xAA00FF00));//边框样式
            polygonOptions.fillColor(Color.parseColor("#00ffffff"));//填充颜色
            //在地图上增加mPolygon 图层
            mPolygon = mBaiduMap.addOverlay(polygonOptions);

        }

    };

    @Override
    protected void setListener() {
        mRightThree.setOnClickListener(this);
    }

    @Override
    protected void processLogic(Bundle savedInstanceState) {
        setCTitle(title);
        setLeftOneBg(R.drawable.ic_back);
        setRightThreeBg(R.drawable.ic_menu);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_rightthree:
                //菜单按钮的点击事件
                mapDrawerMenu.openDrawer(Gravity.END);
                break;
            default:
                break;
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @OnClick({R.id.map_rb_moon, R.id.map_rb_general, R.id.map_rb_3d, R.id.map_img_mtype})
    public void Onclick(View v) {
        switch (v.getId()) {
            case R.id.map_rb_general:
                //卫星地图
                mCurrentMode = NORMAL;
                mBaiduMap
                        .setMyLocationConfiguration(new MyLocationConfiguration(
                                mCurrentMode, true, null));
                mBaiduMap.setMapType(BaiduMap.MAP_TYPE_SATELLITE);
                mapRbGeneral.setTextColor(Color.RED);
                mapRbMoon.setTextColor(defaultColor);
                mapRb3d.setTextColor(defaultColor);
                builder.overlook(0);
                builder.target(ll).zoom(10);
                mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
                break;
            case R.id.map_rb_moon:
                //普通地图
                mCurrentMode = NORMAL;
                mBaiduMap
                        .setMyLocationConfiguration(new MyLocationConfiguration(
                                mCurrentMode, true, null));
                mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
                mapRbMoon.setTextColor(Color.RED);
                mapRbGeneral.setTextColor(defaultColor);
                mapRb3d.setTextColor(defaultColor);
                builder.overlook(0);
                builder.target(ll).zoom(10);
                mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));

                break;
            case R.id.map_rb_3d:
                //3D地图
                mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
                mCurrentMode = LocationMode.COMPASS;
                mBaiduMap
                        .setMyLocationConfiguration(new MyLocationConfiguration(
                                mCurrentMode, true, null));
                mapRbMoon.setTextColor(defaultColor);
                mapRbGeneral.setTextColor(defaultColor);
                mapRb3d.setTextColor(Color.RED);
                builder.target(ll).zoom(20);
                mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
                break;
            case R.id.map_img_mtype:
                switch (mCurrentMode) {
                    case NORMAL:
                        mCurrentMode = FOLLOWING;
                        Glide.with(mContext).load(R.drawable.alk).into(imgMtype);
                        mBaiduMap
                                .setMyLocationConfiguration(new MyLocationConfiguration(
                                        mCurrentMode, true, null));
                        builder.overlook(0);
                        builder.target(ll).zoom(20);
                        mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
                        break;
                    case FOLLOWING:
                        mCurrentMode = COMPASS;
                        Glide.with(mContext).load(R.drawable.alj).into(imgMtype);
                        mBaiduMap
                                .setMyLocationConfiguration(new MyLocationConfiguration(
                                        mCurrentMode, true, null));
                        break;
                    case COMPASS:
                        mCurrentMode = NORMAL;
                        Glide.with(mContext).load(R.drawable.alp).into(imgMtype);
                        mBaiduMap
                                .setMyLocationConfiguration(new MyLocationConfiguration(
                                        mCurrentMode, true, null));
                        builder.overlook(0);
                        builder.target(ll).zoom(20);
                        mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
                        break;
                    default:
                        break;
                }
                break;
            default:
                break;
        }
    }


    @Override
    public void onSensorChanged(SensorEvent sensorEvent) {
//每次方向改变，重新给地图设置定位数据，用上一次onReceiveLocation得到的经纬度、精度
        double x = sensorEvent.values[SensorManager.DATA_X];
        if (Math.abs(x - lastX) > 1.0) {// 方向改变大于1度才设置，以免地图上的箭头转动过于频繁
            mCurrentDirection = (int) x;
            locData = new MyLocationData.Builder().accuracy(mCurrentAccracy)
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(mCurrentDirection).latitude(mCurrentLat).longitude(mCurrentLon).build();

            mBaiduMap.setMyLocationData(locData);

        }
        lastX = x;
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int i) {

    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        if (perms.size() == this.perms.length) {
            initMap();
            initShowView();
            mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION),
                    SensorManager.SENSOR_DELAY_UI);
        }
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {

    }


    public class MyLocationListenner implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            // map view 销毁后不在处理新接收的位置
            if (location == null || mBaiduMap == null) {
                return;
            }
            mCurrentAccracy = location.getRadius();
            mCurrentLat = location.getLatitude();
            mCurrentLon = location.getLongitude();
            locData = new MyLocationData.Builder()
                    .accuracy(location.getRadius())
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(100).latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();
            mBaiduMap.setMyLocationData(locData);
            if (isFirstLoc) {
                isFirstLoc = false;
                ll = new LatLng(location.getLatitude(),
                        location.getLongitude());
                builder = new MapStatus.Builder();
                builder.target(ll).zoom(10);
                mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
            }
        }

        @Override
        public void onConnectHotSpotMessage(String s, int i) {

        }

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        mapMapvShow.onDestroy();
        mSensorManager.unregisterListener(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
        mapMapvShow.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        mapMapvShow.onPause();
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // Forward results to EasyPermissions
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }


}
